package com.ynr.user.service.impl;

import java.util.ArrayList;
import java.util.List;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.ynr.common.utils.SysConstants;
import com.ynr.user.dao.IUserDao;
import com.ynr.user.model.PermissionModel;
import com.ynr.user.model.RoleModel;
import com.ynr.user.model.UserModel;

public class ShiroRealm extends AuthorizingRealm {

	private static final Logger logger = LoggerFactory
			.getLogger(ShiroRealm.class);
	
	@Autowired
	IUserDao userdao;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String email = (String)getAvailablePrincipal(principals);
        if(email != null && !email.isEmpty()) {
        	UserModel userModel = (UserModel)getSession(SysConstants.USER_SESSION_ID);
        	if(userModel != null) {
	            List<RoleModel> roleList = userdao.getRoleModelByUserId(userModel.getUser_id());
	            List<PermissionModel> permList = userdao.getPermissionModelByUserId(userModel.getUser_id());
	            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
	            List<String> roles = new ArrayList<String>();
	            for(RoleModel role : roleList) {
	            	roles.add(role.getName());
	            }
	            List<String> perms = new ArrayList<String>();
	            for(PermissionModel perm : permList) {
	            	perms.add(perm.getPerms());
	            }
	            info.addRoles(roles);
	            info.addStringPermissions(perms);
	            return info;
        	}
        }
        throw new AuthorizationException();
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) {
		UseremailPasswordToken token = (UseremailPasswordToken) authcToken;  
        String email = token.getEmail();  
        if (email != null && !email.isEmpty()) {
            UserModel userModel = userdao.getUserModelByEmail(email);  
            if (userModel != null) {
            	this.setSession(SysConstants.USER_SESSION_ID, userModel);
                return new SimpleAuthenticationInfo(userModel.getEmail(), userModel.getPassword(), getName());  
            }  
        }
        logger.error("doGetAuthorizationInfo login exception, email is null or empty!");
        return null; 
	}
	
	private void setSession(String key, Object value) {
        Subject currentUser = SecurityUtils.getSubject();
        if (null != currentUser) {
            Session session = currentUser.getSession();
            logger.debug("Session默认超时时间为{}毫秒", session.getTimeout());
            if (null != session) {
                session.setAttribute(key, value);
            }
        }
    }
	
	private Object getSession(String key) {
        Subject currentUser = SecurityUtils.getSubject();
        if (null != currentUser) {
            return currentUser.getSession().getAttribute(key);
        } else {
        	return null;
        }
    }

}
